package com.glory.brepda.activity.material;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.brepda.R;
import com.pda.platform.ui.ui_pdaplatform.R.id;
import com.pda.platform.ui.ui_pdaplatform.R.layout;
import com.glory.brepda.adapter.PickingDataAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.entity.DefectCodeEntity;
import com.glory.brepda.entity.PickingEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.MyUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.adapter.FreeUI_NormalPopListAdapter;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextAndPositionCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.OnClick;

public class MaterialRlfAppointmentActivity extends BaseActivity {


    private LinearLayout llMain;
    private NestedScrollView nsScroll;

    // 设备所属车间下拉选择框
    protected FrameLayout flWorkShop;
    protected TextView tvWorkShop;
    protected ImageView ivWorkShop;

    // 一分厂车间数据列表
    protected List<String> workShopList;

    // 一分厂车间数据下拉选择框
    protected FreeUI_GeneralPop workShopPop;
    private MLotAppointmentAdapter mLotAppointmentAdapter;
    protected FreeUI_NormalPopListAdapter workShopPopListAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_material_rlf_appointment;
    }

    @Override
    protected void initView() {

        llMain = findViewById(R.id.llMain);
        nsScroll = findViewById(R.id.nsScroll);
        flWorkShop = findViewById(R.id.flWorkShop);
        tvWorkShop = findViewById(R.id.tvWorkShop);
        ivWorkShop = findViewById(R.id.ivWorkShop);

        RecyclerView rvMLotAppointment = findViewById(R.id.rvMLotAppointment);
        initRecyclerView(rvMLotAppointment, MaterialRlfAppointmentActivity.this);

        // 领料单列表适配器定义，以及点击事件定义
        mLotAppointmentAdapter = new MLotAppointmentAdapter(null);
        mLotAppointmentAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mLotAppointmentAdapter.isFirstOnly(true);
        rvMLotAppointment.setAdapter(mLotAppointmentAdapter);

        // 设定点击事件，点击之后携带信息跳转到 MaterialRlfOutActivity页面进行扫描发料
        mLotAppointmentAdapter.setOnItemClickListener((adapter, view, position) -> {
            PickingEntity item = mLotAppointmentAdapter.getItem(position);
            if (item == null) {
                showToast("领料单数据获取错误，请联系管理员", false);
                return;
            }
            Bundle bundle = new Bundle();
            // 领料单基本信息：主键：后续传到后台进行处理；物料规格、申请数量、设备号、指定的厂家
            bundle.putLong("objectRrn", item.getOBJECTRRN());// 领料单主键
            bundle.putString("materialSpec", item.getMATERIALSPEC());// 领料规格
            bundle.putString("mainQty", item.getMAINQTY());// 申请数量
            bundle.putString("eqpId", item.getEQPID());// 设备号
            bundle.putString("eqpLocation", item.getEQPLOCATION());// 设备位置号
            bundle.putString("reserved5", item.getRESERVED5());// 供应商
            bundle.putString("reserved6", StringUtils.isEmpty(item.getRESERVED6()) ? "0" : item.getRESERVED6());// 领料单已经发料的数量
            // 启动发料页面
            FreeApi_Utils.skipWithExtraIntent("header", bundle, MaterialRlfAppointmentActivity.this, MaterialRlfOutActivity.class);
        });
    }

    @Override
    protected void initData() {

    }

    /**
     * 客制化主标题显示，本次主要重写右边按钮，点击按钮可以显示和隐藏搜索框
     * @return 新的主标题，及其按钮
     */
    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("框架发料");

        freeUI_titleView.setRightListener("隐藏/显示", v -> {
            if (nsScroll.getVisibility() == View.VISIBLE) {
                nsScroll.setVisibility(View.GONE);
                return;
            }
            nsScroll.setVisibility(View.VISIBLE);
        });

        return new FreeUI_AddViewEntity("header", llMain);
    }

    /**
     * 页面第一次运行、从别的activity回来或应用切换回来时会调用该方法
     */
    @Override
    protected void onResume() {
        super.onResume();

        // 一分厂车间数据列表、文本框没有数据的时候请求 一分厂车间数据
        if (workShopList == null
                || (workShopList.size() == 0 && StringUtils.isEmpty(tvWorkShop.getText()))) {
            // 查询设备车间列表
            requestForWorkShopList();
        }

        if (StringUtils.isNotEmpty(String.valueOf(tvWorkShop.getText()))) {
            // 根据选择车间查询框架领料单
            requestForMLotRlfAppointment();
        }
    }

    /**
     * 获取领料单数据
     */
    protected void requestForMLotRlfAppointment() {

        // 检查是否有去填写设备所属区域
        if (MyUtils.checkTextIsEmptyInAnyTextView(false, tvWorkShop)) {
            showToast("信息填写未完成，请检查", false);
            return;
        }

        // 清空原有数据框的数据
        MyUtils.clearDataInAdapter(mLotAppointmentAdapter);

        FreeUI_EntityCallBack<BaseResponseBean<PickingEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<PickingEntity>>
                (new TypeToken<BaseResponseBean<PickingEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<PickingEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {

                    List<PickingEntity> appointmentList = response.body().getResponse().getBody().getPickingEntityList();
                    if (appointmentList != null && appointmentList.size() > 0) {
                        mLotAppointmentAdapter.addData(appointmentList);
                        return;
                    }
                    showConfirmDialog("暂无领料申请");
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<PickingEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PICKAPPOINTMENT");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "QUERY_APPOINTMENT_INFO");
        map.addProperty("MATERIALTYPE", "框架");
        map.addProperty("WORKSHOP", String.valueOf(tvWorkShop.getText()));
        // 25/5/8 901713 后台接口进行了优化，可以自由选择领料单状态进行抓取领料单，故这里需要增加条件：选择状态为创建状态的执行发料
        map.addProperty("STATUS", "CREATED");
        NetUtils.requestPostNet("IF.PICKAPPOINTMENT", "Common", MaterialRlfAppointmentActivity.this, map, callBack);
    }

    /**
     * 获取设备车间数据
     */
    private void requestForWorkShopList() {

        FreeUI_EntityCallBack<BaseResponseBean<DefectCodeEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<DefectCodeEntity>>
                (new TypeToken<BaseResponseBean<DefectCodeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onSuccess(response);

                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<DefectCodeEntity.DefectCode> refList = response.body().getResponse().getBody().getADREFLIST();
                    // 接口返回结果不为空，开始初始化设备所属车间下拉列表
                    if (refList != null && refList.size() > 0) {
                        workShopList = new ArrayList<>(refList.size());
                        for (DefectCodeEntity.DefectCode code : refList) {
                            workShopList.add(code.getKEY());
                        }
                    }
                }

            }

            @Override
            public void onError(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME","WorkShop_NAME");
        map.addProperty("WHERECLAUSE","KEY_ID LIKE '一分厂%'");

        NetUtils.requestPostNet("IF.ADREFLISTQUERY","Common", MaterialRlfAppointmentActivity.this, map, callBack);
    }

    @OnClick({R.id.flWorkShop, R.id.tvReset, R.id.tvSearch})
    public void onViewClicked(View view) {
        // 点击设备所属车间下拉框
        if (view.getId() == R.id.flWorkShop) {
            if (workShopPop != null) {
                if (workShopPop.isShowing()) {
                    workShopPop.dismiss();
                }
            } else {
                // 设置车间选择下拉框为多选框，点击选项时将对应选项加到 文本框里面，并将该选择从数据列表里面去除
                workShopPopListAdapter = new FreeUI_NormalPopListAdapter(workShopList);
                workShopPop = getNormalPop(getApplicationContext(), flWorkShop.getWidth(), workShopPopListAdapter, ivWorkShop, (codeS, i) -> {
                    final String newString = StringUtils.isEmpty(tvWorkShop.getText()) ? codeS : codeS + "," + tvWorkShop.getText();
                    tvWorkShop.setText(newString);
                    // 添加成功之后，去除掉相关的选项，想重新选必须进行重置
                    workShopPopListAdapter.remove(i);
                });
            }
            FreeApi_PopUtils.setArrowShow(ivWorkShop);
            workShopPop.showAsDropDown(flWorkShop, 0, 0);

        } else if (view.getId() == R.id.tvSearch) { // 点击查询，查询领料单信息
            requestForMLotRlfAppointment();
        } else if (view.getId() == R.id.tvReset) { // 点击重置，将搜索条件清空
            // 清除文本框中的数据
            if (StringUtils.isNotEmpty(tvWorkShop.getText())) {
                // 将文本框内的内容重新添加回去，车间数据列表里面
                workShopPopListAdapter.addData(Arrays.asList(StringUtils.split(String.valueOf(tvWorkShop.getText()), ",")));
                tvWorkShop.setText(StringUtils.EMPTY);
            }
        }
    }

    /**
     * 生成下拉选项框，重写该方法主要是能通过Adapter控制里面的数据变化，参考的类：FreeApi_PopUtils，主要魔改的方法是 getNormalPop
     * @param context 主页面
     * @param width 下拉选项框宽度
     * @param popListAdapter 下拉选项框数据适配器
     * @param ivArrow 下拉选项框箭头视图
     * @param textAndPositionCallback 点击具体选项后触发的回调事件
     * @return 下拉选项框实例
     */
    protected FreeUI_GeneralPop getNormalPop(Context context, int width, FreeUI_NormalPopListAdapter popListAdapter, final ImageView ivArrow, final FreeUI_TextAndPositionCallback textAndPositionCallback) {
        View mView = LayoutInflater.from(context).inflate(layout.free_ui_pop_choose_list, (ViewGroup)null);
        RecyclerView recyclerView = mView.findViewById(id.rvList);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        if (FreeUI_NormalPopListAdapter.getResID() != layout.free_ui_blue_sky_normal_pop_list) {
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.addItemDecoration(new DividerItemDecoration(context, 1));
        }

        final FreeUI_GeneralPop generalPop = new FreeUI_GeneralPop(context, mView, width, -2);
        popListAdapter.openLoadAnimation(1);
        popListAdapter.isFirstOnly(true);
        popListAdapter.setOnItemClickListener((adapter, view, position) -> {
            textAndPositionCallback.onSuccess(String.valueOf(adapter.getItem(position)), position);
            generalPop.dismiss();
        });
        recyclerView.setAdapter(popListAdapter);
        generalPop.setOutsideTouchable(true);
        generalPop.setOnDismissListener(() -> FreeApi_PopUtils.setArrowMiss(ivArrow));
        return generalPop;
    }
}

// 框架领料单数据适配器
class MLotAppointmentAdapter extends PickingDataAdapter {

    public MLotAppointmentAdapter(@Nullable List<PickingEntity> data) {
        super(data);
    }

    @Override
    protected void convert(BaseViewHolder helper, PickingEntity item) {
        // 以下栏位取消不要
        helper.getView(R.id.tvLotId).setVisibility(View.GONE);
        helper.getView(R.id.tvStep).setVisibility(View.GONE);

        // 规格
        helper.setText(R.id.tvType, item.getMATERIALSPEC());
        // 数量
        helper.setText(R.id.tvSpec,item.getMAINQTY());
        // 设备号
        helper.setText(R.id.tvEqpId,item.getEQPID());
        // 设备位置号
        helper.setText(R.id.tvEqpLocation,item.getEQPLOCATION());
        // 供应商
        helper.setText(R.id.tvQty,item.getRESERVED5());
    }

}
